package com.pig4cloud.pig.common.mybatis.handler;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pig.common.mybatis.base.FormJson;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import cn.hutool.json.JSONUtil;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author mobai
 */
@MappedTypes(FormJson.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class FormJsonTypeHandler implements TypeHandler<FormJson> {
	static ObjectMapper objectMapper = new ObjectMapper();

	static {
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}

	@SneakyThrows
	@Override
	public void setParameter(PreparedStatement ps, int i, FormJson parameter, JdbcType jdbcType) {
		if (parameter == null) {
			ps.setString(i, null);
		} else {
			String json = JSONUtil.toJsonStr(parameter);
			ps.setString(i, json);
		}

	}

	@SneakyThrows
	@Override
	public FormJson getResult(ResultSet rs, String columnName) {
		if (ObjectUtil.isEmpty(rs.getString(columnName))){
			return new FormJson();
		}
		return JSONUtil.toBean(rs.getString(columnName),FormJson.class);
	}

	@SneakyThrows
	@Override
	public FormJson getResult(ResultSet rs, int columnIndex) {
		if (ObjectUtil.isEmpty(rs.getString(columnIndex))){
			return new FormJson();
		}
		return JSONUtil.toBean(rs.getString(columnIndex),FormJson.class);
	}

	@SneakyThrows
	@Override
	public FormJson getResult(CallableStatement cs, int columnIndex) {
		if (ObjectUtil.isEmpty(cs.getString(columnIndex))){
			return new FormJson();
		}
		return JSONUtil.toBean(cs.getString(columnIndex),FormJson.class);
	}
}
